package com.atguigu.crowd.util;

import com.atguigu.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Scanner;

public class CrowdUtil {
    /**
     * 判断当前请求是否为 Ajax 请求 * @param request
     * @return true 是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
// 1.获取请求消息头信息
        String acceptInformation = request.getHeader("Accept");
        String xRequestInformation = request.getHeader("X-Requested-With");
        // 2.检查并返回
        return
        (
                acceptInformation != null
                        && acceptInformation.length() > 0
                        && acceptInformation.contains("application/json")
        )
                ||
                (
                        xRequestInformation != null
                                && xRequestInformation.length() > 0
                                && xRequestInformation.equals("XMLHttpRequest")
                );
    }

    /**
     * 对明文进行MD5加密
     * @param source 传入的明文字符串
     * @return 加密的结果
     */
    public static String md5(String source){
        if(source == null || source.length() == 0){
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        try {
            // 创建MessageDigest对象，使用算法md5
            String algorithm = "MD5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 获取明文字符串对应的子节数组
            byte[] input = source.getBytes();
            // 执行加密
            byte[] out = messageDigest.digest(input);
            // 创建BigInteger对象 1表示正数
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum,out);
            // 按照16进制将bigInteger的值转换为字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
